//
//  LuYingZhongController.m
//  JianTingSwift
//
//  Created by zhibao on 2024/11/7.
//

#import "LuYingZhongController.h"
#import "BoLangView.h"
#import <AVFoundation/AVFoundation.h>
#define RECORE_BTN_TAG 1010
#define FINISH_BTN_TAG 1011
#define PAUSE_BTN_TAG 1012
#define CORECORE_BTN_TAG 1013
#define CANCEL_BTN_TAG 1014
@interface LuYingZhongController ()<AVAudioRecorderDelegate>{
    UILabel *timeLabel;
    NSTimer *timer,*waveTimer;
    int recordTime,playTime,hour,second,minute;
    
    UIButton *playBtn,*finishBtn,*cancelBtn;
    
    AVAudioRecorder *audioRecorder;
    AVAudioSession * audioSession;
    
    NSURL* saveAudioPath;
    
    NSMutableArray *pointArray;
    
    BoLangView *drawView,*drawView1;
}
@end

@implementation LuYingZhongController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_interactivePopDisabled = YES;
    self.gk_navTitle = LocalizedString(@"录制");
    recordTime = 0;
    [self initView];
}

-(void)initView{
    playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:playBtn];
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(- SafeBottomMargin - 100);
    }];
    [playBtn setImage:[UIImage imageNamed:@"h_r_start"] forState:UIControlStateNormal];
    playBtn.tag = RECORE_BTN_TAG;
    [playBtn addTarget:self action:@selector(opBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    finishBtn = [[UIButton alloc] init];
    [self.view addSubview:finishBtn];
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(playBtn.mas_right).offset(pixw(55));
        make.centerY.equalTo(playBtn);
    }];
    [finishBtn setImage:[UIImage imageNamed:@"h_r_finish"] forState:UIControlStateNormal];
    finishBtn.tag = FINISH_BTN_TAG;
    [finishBtn addTarget:self action:@selector(opBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *cancelButton = [[UIButton alloc] init];
    [self.view addSubview:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(playBtn.mas_left).offset(pixw(-55));
        make.centerY.equalTo(playBtn);
    }];
    [cancelButton setImage:[UIImage imageNamed:@"h_r_cancel"] forState:UIControlStateNormal];
    cancelButton.tag = CANCEL_BTN_TAG;
    [cancelButton addTarget:self action:@selector(opBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    timeLabel = [[UILabel alloc] init];
    [self.view addSubview:timeLabel];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.mas_equalTo( NAVIH + pixw(50));
    }];
    [timeLabel setText:@"00:00:00"];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    [timeLabel setFont:MY_SCALE_BoldFont(50)];
    [timeLabel setTextColor:[UIColor blackColor]];
    
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）, 采样率必须要设为11025才能使转化成mp3格式后不会失真
    [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
    //录音通道数  1 或 2 ，要转换成mp3格式必须为双通道
    [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    //存储录音文件地址
    saveAudioPath = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:[NSString stringWithFormat:@"lz_%@.wav",[Helper getCurrentTimes:@"yyyyMMddHHmmss"]]]];
    
    //初始化
    audioRecorder = [[AVAudioRecorder alloc] initWithURL:saveAudioPath settings:recordSetting error:nil];
    //开启音量检测
    audioRecorder.meteringEnabled = YES;
    audioRecorder.delegate = self;
    
    drawView = [[BoLangView alloc]initWithFrame:CGRectMake(pixw(20), 0, MY_Screen_W - pixw(40), pixw(150))];
    drawView.bottom = self.view.height / 2;
    drawView.backgroundColor = UIColor.clearColor;
    drawView.colorStr = @"#E04148";
    [self.view addSubview:drawView];
    drawView1 = [[BoLangView alloc]initWithFrame:CGRectMake(pixw(20), drawView.bottom, MY_Screen_W - pixw(40), pixw(150))];
    drawView1.backgroundColor = UIColor.clearColor;
    drawView1.colorStr = @"#E04148";
    drawView1.transform = CGAffineTransformMakeScale(1.0, -1.0);
    [self.view addSubview:drawView1];
    pointArray = [NSMutableArray new];
    for(int i = 0; i < 300; i ++ ){
        CGPoint point = CGPointMake(drawView.height, pixw(2));
        [pointArray insertObject:[NSValue valueWithCGPoint:point] atIndex:0];
    }
    drawView.pointArray = pointArray;
    drawView1.pointArray = pointArray;
}

- (void)opBtnClick:(UIButton*)sender {
    audioSession = [AVAudioSession sharedInstance];//得到AVAudioSession单例对象
    switch (sender.tag) {
        case RECORE_BTN_TAG:{
            if (![audioRecorder isRecording]) {
                //设置类别,表示该应用同时支持播放和录音
                [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord mode:AVAudioSessionModeVoiceChat options:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
                //启动音频会话管理,此时会阻断后台音乐的播放.
                [audioSession setActive:YES error:nil];
                
                [audioRecorder prepareToRecord];
                [audioRecorder peakPowerForChannel:0.0];
                [audioRecorder record];
                
                [self recordTimeStart];
                [sender setImage:[UIImage imageNamed:@"h_r_pluse"] forState:UIControlStateNormal];
                sender.tag = PAUSE_BTN_TAG;
            }else{
                //录音停止
                [audioRecorder stop];
                //一定要在录音停止以后再关闭音频会话管理（否则会报错），此时会延续后台音乐播放
                [audioSession setActive:NO error:nil];
                //取消录制时间
                [timer invalidate];
                //取消波浪时间
                [waveTimer invalidate];
                //时间显示复位
                [timeLabel setText:@"00:00:00"];
            }
        }
            break;
            
        case PAUSE_BTN_TAG:{
            [audioRecorder pause];
            [audioSession setActive:NO error:nil];
            [timer invalidate];
            [waveTimer invalidate];
            sender.tag = CORECORE_BTN_TAG;
            [sender setImage:[UIImage imageNamed:@"h_r_start"] forState:UIControlStateNormal];
        }
            break;
        case CORECORE_BTN_TAG:{
            [audioRecorder record];
            [audioSession setActive:YES error:nil];
            [timer invalidate];
            [waveTimer invalidate];
            [self recordTimeStart];
            [sender setImage:[UIImage imageNamed:@"h_r_pluse"] forState:UIControlStateNormal];
            sender.tag = PAUSE_BTN_TAG;
        }
            break;
        case CANCEL_BTN_TAG:{
            if([timeLabel.text isEqualToString:@"00:00:00"]){
                [QMUITips showError:LocalizedString(@"当前没有录音文件可以删除！")];
                return;
            }
            [Helper alertShowWithTitle:LocalizedString(@"是否取消？") withContent:LocalizedString(@"点击是,文件不会被保存!") withSureBtnTitle:LocalizedString(@"是") withCancelBtnTitle:LocalizedString(@"否") withSelect:^(NSInteger index) {
                if(index == 1){
                    [self->audioRecorder stop];
                    [self->audioSession setActive:NO error:nil];
                    [self->timer invalidate];
                    [self->waveTimer invalidate];
                    [self->timeLabel setText:@"00:00:00"];
                    self->recordTime = 0;
                    self->playBtn.tag = RECORE_BTN_TAG;
                    [self->playBtn setImage:[UIImage imageNamed:@"h_r_start"] forState:UIControlStateNormal];
                    [self stop];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }];
        }
            break;
        case FINISH_BTN_TAG:{
            if([timeLabel.text isEqualToString:@"00:00:00"]){
                [QMUITips showError:LocalizedString(@"请先开始录制")];
                return;
            }
            [self->pointArray removeAllObjects];
            for(int i = 0; i < 300; i ++ ){
                CGPoint point = CGPointMake(self->drawView.height, 2);
                [self->pointArray insertObject:[NSValue valueWithCGPoint:point] atIndex:0];
            }
            self->drawView.pointArray = self->pointArray;
            self->drawView1.pointArray = self->pointArray;
            [audioRecorder stop];
            [audioSession setActive:NO error:nil];
            [timer invalidate];
            [waveTimer invalidate];
            recordTime = 0;
            playBtn.tag = RECORE_BTN_TAG;
            [playBtn setImage:[UIImage imageNamed:@"h_r_start"] forState:UIControlStateNormal];
            [QMUITips showLoading:@"...上传中..." inView:self.view];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 4), ^{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Helper saveData:@[self->saveAudioPath.absoluteString,self->saveAudioPath.lastPathComponent] withDocum:self.docum withType:DOCUMENTYPE];
                    [QMUITips hideAllTips];
                    [QMUITips showSucceed:LocalizedString(@"保存成功！")];
                    [self->timeLabel setText:@"00:00:00"];
                    [self stop];
                    [self.navigationController popViewControllerAnimated:true];
                });
            });
        }
            break;
    }
}

- (void)recordTimeStart {
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordTimeTick) userInfo:nil repeats:YES];
    waveTimer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(waveTimeTick) userInfo:nil repeats:YES];
}

-(void)waveTimeTick{
    [audioRecorder updateMeters];
        
        float   level;                // The linear 0.0 .. 1.0 value we need.
        float   minDecibels = -60.0f; // use -80db Or use -60dB, which I measured in a silent room.
        float   decibels    = [audioRecorder averagePowerForChannel:0];
        
        if (decibels < minDecibels)
        {
            level = 0.0f;
        }
        else if (decibels >= 0.0f)
        {
            level = 1.0f;
        }
        else
        {
            float   root            = 5.0f; //modified level from 2.0 to 5.0 is neast to real test
            float   minAmp          = powf(10.0f, 0.05f * minDecibels);
            float   inverseAmpRange = 1.0f / (1.0f - minAmp);
            float   amp             = powf(10.0f, 0.05f * decibels);
            float   adjAmp          = (amp - minAmp) * inverseAmpRange;
            
            level = powf(adjAmp, 1.0f / root);
        }
        
        /* level 范围[0 ~ 1], 转为[0 ~120] 之间 */
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"voice updated :%f",level * 100);
        });
    CGFloat templevel = level * drawView.height;
    if (templevel < 1){
        templevel = pixw(2);
    }
    CGPoint point = CGPointMake(drawView.height, templevel);
    [pointArray insertObject:[NSValue valueWithCGPoint:point] atIndex:0];
    [pointArray removeLastObject];
    drawView.pointArray = pointArray;
    drawView1.pointArray = pointArray;
}

- (void)recordTimeTick {
    recordTime += 1;
    [self updateAudioRecordTime];
}

- (void)updateAudioRecordTime {

    second = recordTime % 60;
    minute = recordTime / 60;
    hour = minute / 60;
    [timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d",hour,minute,second]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self stop];
}

- (void)dealloc{
    [self stop];
}

-(void)stop{
    [timer invalidate];
    [waveTimer invalidate];
    [audioRecorder stop];
    [audioRecorder deleteRecording];
}

@end

